import React from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { Form, Icon, Input, Button, message } from 'antd';
import styles from './Ready.css';

const FormItem = Form.Item;
class Ready extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      roomnum: null,
    };
  }

  establish = () => {
    const roomNum = Math.floor(Math.random() * 9000) + 1000;
    const userName = this.props.data.username;
    this.props.dispatch({
      type: 'ready/establish',
      payload: { roomNum, userName },
    });
  }

  join = () => {
    const userName = this.props.data.username;
    const roomNum = this.state.roomnum;
    this.props.dispatch({
      type: 'ready/establish',
      payload: { roomNum, userName },
    });
  }

  handleChange=(e) => {
    const roomnum = parseInt(e.target.value || 0, 10);
    if (isNaN(roomnum)) {
      return;
    }
    this.setState({ roomnum });
  }

  componentWillReceiveProps(nextProps) {
    const data = nextProps.data;
    if (data.code) {
      switch (data.code) {
        case 200:
          data.householder === data.username ? message.success('创建成功！') : message.success('加入成功！');
          this.props.dispatch(routerRedux.push('/room'));
          break;
        case 404:
          data.householder === data.username ? message.error('创建失败！') : message.error('加入失败！');
          break;
        default:
          message.error('服务器错误，请重试！');
      }
    }
  }

  render() {
    return (
      <div className={styles.normal} >
        <Form layout="inline">
          <FormItem>
            <Button
              type="primary"
              htmlType="button"
              onClick={this.establish}
            >
              创建房间
            </Button>
          </FormItem>
          <FormItem >
            {
              <Input
                prefix={<Icon type="smile" style={{ color: 'rgba(0,0,0,.25)' }} />}
                placeholder="请输入房间号"
                onChange={this.handleChange}
              />
            }
          </FormItem>
          <FormItem>
            <Button
              type="primary"
              htmlType="button"
              onClick={this.join}
            >
              加入
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }

}

const ReadyForm = Form.create()(Ready);
function mapStateToProps(state) {
  const data = state.ready.data;
  data.username = state.login.data.username;
  return { data };
}

export default connect(mapStateToProps)(ReadyForm);
